import { Controller, Post, UseInterceptors, UploadedFile, UploadedFiles } from "@nestjs/common";
import { FileInterceptor, FilesInterceptor } from "@nestjs/platform-express";
import { diskStorage } from "multer";
import { extname } from "path";
import { Public } from "src/decorators/is-public.decorator";

@Controller('upload')
export class FileUploadController {

    // @FileInterceptor + @UploadedFile
    @Public()
    @Post('single')
    @UseInterceptors(FileInterceptor('file', {
        // storage for uploaded file
        storage: diskStorage({
            destination: './uploads',
            filename: (req, file, callback) => {
                const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
                const ext = extname(file.originalname);
                const filename = `${file.fieldname}-${uniqueSuffix}${ext}`;
                callback(null, filename);
            },
        }),
        // file filter for uploaded file
        fileFilter: (req, file, callback) => {
            if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
                return callback(new Error('Only image files are allowed!'), false);
            }
            callback(null, true);
        },
        // limits for uploaded file
        limits: { fileSize: 1024 * 1024 * 5 }
    }))
    async uploadSingleFile(@UploadedFile() file: Express.Multer.File) {
        // handle for finish upload file
        return {
            message: 'File uploaded successfully',
            fileInfo: {
                filename: file.filename,
                originalname: file.originalname,
                size: file.size / 1024 / 1024 + 'Mb',
                mimetype: file.mimetype,
                path: file.path,
            },
        }
    }

    // @FilesInterceptor for multiple files upload + @UploadedFiles
    @Public()
    @Post('multiple')
    @UseInterceptors(FilesInterceptor('files', 5, { // 2nd parameter: maximum file number
        storage: diskStorage({
            destination: './uploads',
            filename: (req, file, callback) => {
                const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
                const ext = extname(file.originalname);
                const filename = `${file.fieldname}-${uniqueSuffix}${ext}`;
                callback(null, filename);
            },
        }),
        fileFilter: (req, file, callback) => {
            const ext = extname(file.originalname);
            const allowedExt = ['.jpg', '.jpeg', '.png', '.pdf', '.docx'];
            if (!allowedExt.includes(ext)) {
                return callback(new Error('仅支持 jpg、jpeg、png、pdf、docx 格式！'), false);
            }
            callback(null, true);
        },
        limits: { fileSize: 5 * 1024 * 1024 }, // Maximum file size: 5MB
    }),
    )
    uploadMultipleFiles(@UploadedFiles() files: Express.Multer.File[]) {
        return {
            message: `Upload ${files.length} Files`,
            filesInfo: files.map(file => ({
                filename: file.filename,
                originalname: file.originalname,
                size: file.size / 1024 / 1024 + 'Mb',
                path: file.path,
            })),
        };
    }
}